package com.chatplus.application.controller.admin.biz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.domain.entity.basedata.ApiKeyEntity;
import com.chatplus.application.domain.request.ApiKeySaveRequest;
import com.chatplus.application.domain.request.FiledUpdateRequest;
import com.chatplus.application.domain.response.admin.ApiKeyDetailResponse;
import com.chatplus.application.service.basedata.ApiKeyService;
import com.chatplus.application.web.basecontroller.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/admin/apikey")
@Tag(name = "后台操作APIKEY API", description = "后台操作APIKEY API")
public class ApiKeyAdminApiController extends BaseController {

    private final ApiKeyService apiKeyService;

    public ApiKeyAdminApiController(ApiKeyService apiKeyService) {
        this.apiKeyService = apiKeyService;
    }

    @GetMapping("/list")
    @Operation(summary = "后台获取APIKEY列表")
    public List<ApiKeyDetailResponse> list() {
        LambdaQueryWrapper<ApiKeyEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(ApiKeyEntity::getCreatedAt);
        List<ApiKeyEntity> list = apiKeyService.list(queryWrapper);
        return list.stream().map(ApiKeyDetailResponse::build).toList();
    }

    @GetMapping("/channelList")
    @Operation(summary = "渠道列表")
    public List<String> channelList() {
        // 通过聚合获取channel列表
        return apiKeyService.listObjs(new LambdaQueryWrapper<ApiKeyEntity>()
                .select(ApiKeyEntity::getChannel)
                .eq(ApiKeyEntity::getEnabled, Boolean.TRUE)
                .groupBy(ApiKeyEntity::getChannel), Object::toString);
    }


    @PostMapping("/save")
    @Operation(summary = "后台保存更新APIKEY")
    public ApiKeyDetailResponse save(@RequestBody ApiKeySaveRequest apiKeySaveRequest) {
        // 查询数据库，根据channel查询，不能同时共存于两个platform
        List<ApiKeyEntity> list = apiKeyService.list(new LambdaQueryWrapper<ApiKeyEntity>()
                .eq(ApiKeyEntity::getChannel, apiKeySaveRequest.getChannel())
                .ne(ApiKeyEntity::getPlatform, apiKeySaveRequest.getPlatform()));
        if (CollectionUtils.isNotEmpty(list)) {
            throw new BadRequestException("同个渠道不能同时共存不同平台");
        }
        ApiKeyEntity apiKeyEntity = apiKeyService.getById(apiKeySaveRequest.getId());
        if (apiKeyEntity == null) {
            apiKeyEntity = new ApiKeyEntity();
        }
        apiKeyEntity.setApiUrl(apiKeySaveRequest.getApiUrl());
        apiKeyEntity.setPlatform(apiKeySaveRequest.getPlatform());
        apiKeyEntity.setType(apiKeySaveRequest.getType());
        apiKeyEntity.setValue(apiKeySaveRequest.getValue());
        apiKeyEntity.setUseProxy(apiKeySaveRequest.isUseProxy());
        apiKeyEntity.setEnabled(apiKeySaveRequest.isEnabled());
        apiKeyEntity.setProxyUrl(apiKeySaveRequest.getProxyUrl());
        apiKeyEntity.setReserved(apiKeySaveRequest.getReserved());
        apiKeyEntity.setChannel(apiKeySaveRequest.getChannel());
        apiKeyEntity.setNotifyUrl(apiKeySaveRequest.getNotifyUrl());
        apiKeyService.saveOrUpdate(apiKeyEntity);
        apiKeyService.init();
        return ApiKeyDetailResponse.build(apiKeyEntity);
    }

    @GetMapping("/remove")
    @Operation(summary = "管理员删除APIKEY")
    public void remove(@RequestParam(value = "id") Long id) {
        apiKeyService.removeById(id);
        apiKeyService.init();
    }

    @PostMapping("/set")
    @Operation(summary = "管理员设置APIKEY状态")
    public void set(@RequestBody FiledUpdateRequest request) {
        apiKeyService.update(new UpdateWrapper<ApiKeyEntity>()
                .set(request.getFiled(), Boolean.valueOf(request.getValue()))
                .eq("id", Long.valueOf(request.getId())));
        apiKeyService.init();
    }
}
